package com.yidu.web.listener;

import com.yidu.web.dao.CrosstalkDao;
import com.yidu.web.model.Crosstalklist;
import com.yidu.web.utils.HTMLTools;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class SpiListener implements ServletContextListener {

    public static Map<String, Crosstalklist> map = null ;

    CrosstalkDao crosstalkDao = new CrosstalkDao();

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //初始化时执行
        System.out.println("tomcat已经启动");
        //启动线程
        new MyThread().start();

    }

    class MyThread extends Thread{
        @Override
        public void run() {
            while (true){
                map = crosstalkDao.selectFlag();
                try {
                    List<Crosstalklist> list = HTMLTools.paCrossTalkTitle(HTMLTools.URL);
                    for(Crosstalklist crosstalklist:list){
                        if(map.get(crosstalklist.getFlag()) == null){
                            crosstalkDao.insert(crosstalklist);
                        }
                    }

                    Thread.sleep(1000*60*60);

                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //销毁时执行
    }
}
